# -*- encoding: utf-8 -*-

"""
@File:      tc_popt_fun_001.py
@Time:      2024-02-26 10:09:55
@Author:    qintingting
@Version:   1.0
@Contact:   wb-qtt862918@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    qintingting
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_popt_fun_001.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "popt popt-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline='''cat > popt_fun_001.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <popt.h>

int main(int argc, const char **argv) {
    int intVal;
    long longVal;
    float floatVal;
    double doubleVal;
    char *stringVal;

    struct poptOption options[] = {
        {"int", 'i', POPT_ARG_INT, &intVal, 0, "An integer argument", "INT"},
        {"long", 'l', POPT_ARG_LONG, &longVal, 0, "A long integer argument", "LONG"},
        {"float", 'f', POPT_ARG_FLOAT, &floatVal, 0, "A floating point argument", "FLOAT"},
        {"double", 'd', POPT_ARG_DOUBLE, &doubleVal, 0, "A double-precision floating point argument", "DOUBLE"},
        {"string", 's', POPT_ARG_STRING, &stringVal, 0, "A string argument", "STRING"},
        POPT_AUTOHELP
        POPT_TABLEEND
    };

    poptContext optCon = poptGetContext(NULL, argc, argv, options, 0);
    int rc;

    while ((rc = poptGetNextOpt(optCon)) >= 0) {
        // Can handle options if required
    }

    if (rc < -1) { // Error in parsing
        fprintf(stderr, "Error: %s\\n", poptStrerror(rc));
        return 1;
    }

    // 以下部分是查看解析出的参数值
    printf("String value: %s\\n", stringVal);
    printf("Integer value: %d\\n", intVal);
    printf("Long value: %ld\\n", longVal);
    printf("Float value: %f\\n", floatVal);
    printf("Double value: %lf\\n", doubleVal);

    poptFreeContext(optCon);
    return 0;
}
EOF
'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o popt_fun_001 popt_fun_001.c -lpopt")
        code, result = self.cmd("file popt_fun_001")
        self.assertIn("executable", result)
        code, result = self.cmd("./popt_fun_001 --int 123 --long 12345678 --float 12.34 --double 56.78 --string 'Hello  World'")
        if code == 0:
            print("命令解析成功")
        else:
            raise Exception("命令解析失败")
        self.assertIn("123", result)
        self.assertIn("12345678", result)
        self.assertIn("12.34", result)
        self.assertIn("56.78", result)
        self.assertIn("Hello  World", result)
        
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf popt_fun_001 popt_fun_001.c")
